﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DAL;
using System.Web.Script.Serialization;
using System.Collections.Generic;

namespace WeChat.Common
{
    public class GetTicket
    {
        //验证并返回ticket
        public static string getTicket()
        {
            GetJsapi_ticketDAL fd = new GetJsapi_ticketDAL();
            //从数据库得到ticket
            string ticket = fd.getJsTicket();

            //判断ticket是否过期
            if (ticket.Equals("overtime"))
            {
                //如果过期就重新发送url请求，获得json数据转换成字典类型
                string accesstoken = GetAccess_token.getAccesstoken();
                string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=jsapi";

                var js = new JavaScriptSerializer();
                var dic = js.Deserialize<Dictionary<string, object>>(new GetReturnJson().getReturnJson(url));
                //Dictionary<string, object> dic = new GetReturnJson().getReturnJson(url);

                //判断返回数据是否正确，不正确则返回空值
                if (dic.ContainsKey("ticket"))
                {
                    //得到最新ticket值，并更新到数据库
                    ticket = dic["ticket"].ToString();
                    string expires_in = dic["expires_in"].ToString();
                    int i = fd.updateJsTicket(expires_in, ticket);
                    if (i > 0)
                    {
                        ApplicationLog.Write("更新ticket成功：" + ticket);
                    }
                    return ticket;
                }
                else
                {
                    string errcode = dic["errcode"].ToString();
                    ApplicationLog.Write("请求错误，errcode：" + errcode);
                    return "";
                }
            }
            else
            {
                //ApplicationLog.Write("请求ticket：" + ticket);
                return ticket;
            }
        }
    }
}
